﻿using System.Reflection;
using Devonline.Core;

var commandLine = new CommandLineArgumentParser(args);
var help = commandLine.GetValue<string>("-h") ?? commandLine.GetValue<string>("--help");

if (!string.IsNullOrWhiteSpace(help))
{
    Console.WriteLine("File destory tools usage: fileTools [OPTION].. [ARGUMENTS]");
    Console.WriteLine("-h | --help          display help information");
    Console.WriteLine("-f | --file          destory file(s)");
    Console.WriteLine("-d | --dir           destory directory or directories contents files");
    Console.WriteLine("-r | --recursive     destory directories and their contents recursively");
    return;
}

var argFile = commandLine.GetValue<string>("-f") ?? commandLine.GetValue<string>("--file");
var argDir = commandLine.GetValue<string>("-d") ?? commandLine.GetValue<string>("--dir");
var recursive = commandLine.Has("-r") || commandLine.GetValue<bool>("--recursive");

Console.WriteLine("File Tools will destory the files or directories");

if (!string.IsNullOrWhiteSpace(argFile))
{
    var files = argFile.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var file in files)
    {
        if (File.Exists(file))
        {
            //TODO 使用 FileService 方式文件销毁服务暂不实现
            //await FileUtility.DestoryAsync(file);
            Console.WriteLine($"file: {file} has been destoried!");
        }
        else
        {
            Console.WriteLine($"file: {file} does not exist!");
        }
    }
}

if (!string.IsNullOrWhiteSpace(argDir))
{
    if (argDir == "./")
    {
        argDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    }

    if (!string.IsNullOrWhiteSpace(argDir))
    {
        var directories = argDir.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var dir in directories)
        {
            await DestoryDirectoryAsync(dir, recursive);
        }
    }
}

static async Task DestoryDirectoryAsync(string dir, bool recursive = false)
{
    if (Directory.Exists(dir))
    {
        var files = Directory.GetFiles(dir);
        foreach (var file in files)
        {
            //TODO 使用 FileService 方式文件销毁服务暂不实现
            //await FileUtility.DestoryAsync(file);
            Console.WriteLine($"file: {file} has been destoried!");
        }

        if (recursive)
        {
            var subDirs = Directory.GetDirectories(dir);
            foreach (var subDir in subDirs)
            {
                await DestoryDirectoryAsync(subDir, true);
            }
        }

        Directory.Delete(dir, true);
        Console.WriteLine($"directory: {dir} has been destoried!");
    }
    else
    {
        Console.WriteLine($"directory: {dir} does not exist!");
    }
}